import { Button, DatePicker, Form, Select } from 'antd';
import React, { Fragment, ReactNode } from 'react';
import { connect } from 'dva';
import { withRouter } from 'react-router-dom';
import moment from 'moment';

import { setCommonFun } from '@/utils/tools';
import { getAbnormalColumns } from './utils';
import { getMerchant } from '../service';
import Mtable from '../components/Mtable/index';
import { SUCCESS_CODE } from '../data';
import { initialTimeWithMill, StateType, PropType } from '../utils';

const FormItem = Form.Item;
const { RangePicker } = DatePicker;
const { Option } = Select;

// 初始化表单筛选项
function initTableFilters(): object {
  return {
    userType: '-1',
    errorStatus: '-1',
  };
}

// @ts-ignore
@setCommonFun
class Abnormal extends React.PureComponent<PropType, StateType> {
  public state: StateType = {
    tableFilters: initTableFilters(),
    merchantList: [],
  };

  public refMtable: any;

  componentDidMount() {
    this.getMerchantList();
  }

  // 渲染表单
  private renderFilters = (): ReactNode => {
    const { getFieldDecorator } = this.props.form;
    const { merchantList } = this.state;

    return (
      <Form layout="inline" onSubmit={this.handleSubmit}>
        {/* 充值时间 */}
        <FormItem label="充值时间">
          {getFieldDecorator('time', {
            initialValue: initialTimeWithMill(3),
          })(
            <RangePicker
              showTime={{
                hideDisabledOptions: true,
                defaultValue: [moment('00:00:00', 'HH:mm:ss'), moment('23:59:59', 'HH:mm:ss')],
              }}
              format="YYYY-MM-DD HH:mm:ss"
              placeholder={['开始时间', '结束时间']}
            />,
          )}
        </FormItem>

        {/* 充值商户 */}
        <FormItem label="充值商户">
          {getFieldDecorator('channelId', {
            initialValue: -1,
          })(
            <Select
              style={{ width: 120 }}
              showSearch
              filterOption={(input, option: any) => option.props.children.indexOf(input) >= 0}
            >
              <Option value={-1}>全部</Option>
              {merchantList.map((item: any) => (
                <Option key={item.channelId} value={item.channelId}>
                  {item.channelName}
                </Option>
              ))}
            </Select>,
          )}
        </FormItem>

        <FormItem>
          {/* 搜索 */}
          <Button type="primary" htmlType="submit">
            搜索
          </Button>
          {/* 重置 */}
          <Button style={{ marginLeft: '10px' }} onClick={this.handleReset}>
            重置
          </Button>
        </FormItem>
      </Form>
    );
  };

  // 渲染表格
  renderTable = (): ReactNode => {
    const { abnormalData } = this.props.recharge;
    return (
      <Mtable
        style={{ wordBreak: 'break-all' }}
        dataSource={abnormalData}
        columns={getAbnormalColumns(this)}
        dispatch={this.props.dispatch}
        scroll={{ x: 1500, y: 540 }}
        effectType="recharge/getAbnormalListEffect"
        validateFields={this.props.form.validateFieldsAndScroll}
        setEffectParams={this.setEffectParams}
        ref={(element: ReactNode) => {
          this.refMtable = element;
        }}
      />
    );
  };

  // 获取充值商户
  private getMerchantList = () => {
    getMerchant().then((res: any) => {
      if (res) {
        const { code, data } = res;
        if (code === SUCCESS_CODE && data) {
          this.setState({ merchantList: data });
        }
      }
    });
  };

  // 重置
  private handleReset = () => {
    this.props.form.resetFields();
    this.setState(
      {
        tableFilters: initTableFilters(),
      },
      () => {
        this.refMtable.getTableData();
      },
    );
  };

  // 提交
  private handleSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    this.refMtable.initPage(() => this.refMtable.getTableData());
  };

  // 处理表头筛选项
  private setEffectParams = (filters?: any) => {
    if (filters) {
      const tableFiltersData = {};
      Object.keys(filters).forEach(item => {
        tableFiltersData[item] = filters[item]['0'] || '-1';
      });
      const { tableFilters } = this.state;
      const data = { ...tableFilters, ...tableFiltersData };
      this.setState({ tableFilters: data });
      return data;
    }
    return this.state.tableFilters;
  };

  UNSAFE_componentWillMount() {
    this.getMerchantList();
  }

  render(): ReactNode {
    return (
      <Fragment>
        {this.renderFilters()}
        {this.renderTable()}
      </Fragment>
    );
  }
}

const AbnormalContainer = Form.create({ name: 'rechargeAbnormal' })(Abnormal);

export default withRouter(
  connect(({ recharge }: { recharge: any }) => ({
    recharge,
  }))(AbnormalContainer),
);
